package TangramBase;

import java.awt.Frame;
import javax.swing.*;
import java.awt.*;
import TangramCore.ProgressListener;

public class ProgressFrame extends JDialog implements ProgressListener{
	static final long serialVersionUID = 24362462L;
	
	JProgressBar pgbProgress;
    JLabel lblProgress;
    String sText;
    public boolean success = false, done = false;
    
    int val, min, max;
    
    private void setValue(int val){
        pgbProgress.setValue(val);
        //pgbProgress.paintImmediately(0,0,pgbProgress.getWidth(),pgbProgress.getHeight());
    }
    private void setText(){
        lblProgress.setText(sText + " " + pgbProgress.getValue() + " of " + pgbProgress.getMaximum());
        //lblProgress.paintImmediately(0,0,lblProgress.getWidth(),lblProgress.getHeight());
    }
    
    private Runnable changed = new Runnable(){
        public void run(){
            setValue(val);
            setText();
        }
    };
    
    private Runnable start = new Runnable(){
        public void run(){
            pgbProgress.setMinimum(min);
            pgbProgress.setMaximum(max);
            setValue(min);
            setText();
        }
    };
    
    private Runnable end = new Runnable(){
        public void run(){
            setVisible(false);
        }
    };
    
    public void progressChanged(int val){
        this.val = val;
        try{
            SwingUtilities.invokeAndWait(changed);
        } catch(Exception ex){}
    }
    
    public void progressStart(int min, int max){
        this.min = min;
        this.max = max;
        try{
            SwingUtilities.invokeAndWait(start);
        } catch(Exception ex){}
        //show();
    }
    public void progressEnd(boolean success){
        done = true;
        this.success = success;
        try{
            SwingUtilities.invokeAndWait(end);
        } catch(Exception ex){}
    }
    
    public void init(Frame frame, String title, String text){
        Rectangle r = frame.getBounds();
        setLocation(r.x + (r.width-getWidth())/2,r.y+(r.height-getHeight())/2);
        sText = text;
        setTitle(title);
        done = false;
    }
    
    public ProgressFrame(Frame owner) {
        super(owner, true);
        setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
        Container pane = getContentPane();
        pane.setLayout(new BorderLayout(20,20));//new BoxLayout(this,BoxLayout.Y_AXIS));
        lblProgress = new JLabel("Please wait...");
        pgbProgress = new JProgressBar();
        pgbProgress.setStringPainted(true);
        pane.add(lblProgress, BorderLayout.CENTER);
        pane.add(pgbProgress, BorderLayout.SOUTH);
        setSize(400,100);
        setResizable(false);
    }
}
